<template>
  <div class="bill-statement">
    <a-row
        :wrap="true"
        type="flex"
        justify="space-between"
        align="middle"
        class="tab-row"
    >
      <a-tabs v-model:activeKey="activeTab" @change="onTabChange">
        <a-tab-pane
            v-for="item of statementTabs"
            :key="item.key"
            :tab="item.title"
        ></a-tab-pane>
      </a-tabs>
    </a-row>

    <section class="statistics">
      <a-row class="quantity" type="flex">
        <a-col class="text-center" v-if="isOverdueIncomeTable">
          <div class="number-width">{{ basicsInfo?.total || 0 }}</div>
          <div class="text">总逾期收款单数</div>
        </a-col>
        <a-col class="text-center" v-if="isOverdueIncomeTable">
          <div class="number-width">
            ￥{{ basicsInfo?.overduePriceTotal || 0 }}
          </div>
          <div class="text">总逾期收款金额</div>
        </a-col>
        <a-col class="text-center" v-if="isOverdueIncomeTable">
          <div class="number-width">
            {{ basicsInfo?.overdueOwnerTotal || 0 }}
          </div>
          <div class="text">逾期{{ $L("租客") }}数</div>
        </a-col>
        <a-col class="text-center" v-if="isOverdueIncomeTable">
          <div class="number-width">
            ￥{{ basicsInfo?.overdueLatefeeTotal || 0 }}
          </div>
          <div class="text">滞纳金金额</div>
        </a-col>
        <a-col class="text-center" v-if="isOverdueExpenseTable">
          <div class="number-width">{{ basicsInfo?.total || 0 }}</div>
          <div class="text">总逾期付款单数</div>
        </a-col>
        <a-col class="text-center" v-if="isOverdueExpenseTable">
          <div class="number-width">
            ￥{{ basicsInfo?.overduePriceTotal || 0 }}
          </div>
          <div class="text">总逾期付款金额</div>
        </a-col>
        <a-col class="text-center" v-if="isOverdueExpenseTable">
          <div class="number-width">
            {{ basicsInfo?.overdueOwnerTotal || 0 }}
          </div>
          <div class="text">逾期收款方数</div>
        </a-col>
      </a-row>
    </section>

    <a-form layout="vertical">
      <a-row :wrap="true" class="search-row" :gutter="18" align="middle">
        <!--   逾期账单查询   -->
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="账单来源" :colon="false">
            <a-cascader
                v-model:value="searchParams.bill_source"
                :options="billSourceOption"
                expand-trigger="hover"
                placeholder="请选择"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="费用类型" :colon="false">
            <a-cascader
                v-model:value="searchParams.cost_type"
                :options="costTypeOption"
                :load-data="getCostTypeSub"
                placeholder="请选择"
                dropdownClassName="fee-type-cascader-custom"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="滞纳金状态" :colon="false">
            <a-select
                v-model:value="searchParams.latefee_status"
                :options="lateFeeOption"
                placeholder="请选择"
                :allowClear="true"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="起始时间" :colon="false">
            <a-date-picker
                class="w-100p"
                v-model:value="searchParams.start_date"
                placeholder="开始时间"
                :valueFormat="dateFormatStr"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="结束时间" :colon="false">
            <a-date-picker
                class="w-100p"
                v-model:value="searchParams.end_date"
                placeholder="结束时间"
                :valueFormat="dateFormatStr"
            />
          </a-form-item>
        </a-col>
        <!--        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">-->
        <!--          <a-form-item label="币种" :colon="false">-->
        <!--            <a-select-->
        <!--              v-model:value="searchParams.currency"-->
        <!--              :options="currencyOption"-->
        <!--              placeholder="请选择"-->
        <!--              :allowClear="true"-->
        <!--            />-->
        <!--          </a-form-item>-->
        <!--        </a-col>-->
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="创建时间" :colon="false">
            <a-range-picker
                v-model:value="searchParams.createdTime"
                :placeholder="['开始时间', '结束时间']"
                :value-format="dateFormatStr"
                @change="handleRangePickerChange"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="结清状态" :colon="false">
            <a-select
                v-model:value="searchParams.settle_status"
                placeholder="请选择"
                :options="overdueSettleOptions"
                mode="multiple"
                optionFilterProp="label"
                allowClear
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item
              :label="isOverdueIncomeTable ? '应收时间' : '应付时间'"
              :colon="false"
          >
            <a-range-picker
                v-model:value="searchParams.receivableTime"
                :placeholder="['开始时间', '结束时间']"
                :value-format="dateFormatStr"
                @change="handleReceivablePickerChange"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="项目名称" :colon="false">
            <a-select
                v-model:value="searchParams.village_ids"
                :options="villageList"
                placeholder="请选择项目"
                :allowClear="true"
                mode="multiple"
                optionFilterProp="label"
                style="width: 100%"
                @change="onVillageChange"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="楼宇名称" :colon="false">
            <a-select
                v-model:value="searchParams.build_ids"
                :options="buildList"
                placeholder="请选择楼宇"
                :allowClear="true"
                mode="multiple"
                optionFilterProp="label"
                style="width: 100%"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item
              :label="`${BLCOMMON.utils.L('租客')}名称`"
              :colon="false"
          >
            <a-input
                :placeholder="`请输入${BLCOMMON.utils.L('租客')}名称`"
                v-model:value="searchParams.keywords"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="所属公司" :colon="false">
            <a-select
                v-model:value="searchParams.org_branch_id"
                :options="companyList"
                placeholder="请选择所属公司"
                :allowClear="true"
                mode="multiple"
                optionFilterProp="label"
                style="width: 100%"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item label=" ">
            <a-space>
              <a-button type="primary" @click="handleSearch"> 查询</a-button>
              <a-button @click="reset">重置</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <!-- 非调整金表格 -->
    <div class="statement-content">
      <a-table
          sticky
          :dataSource="dataList"
          :columns="overdueColumns"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          rowKey="id"
          :scroll="{ x: 'max-content' }"
          :row-selection="rowSelection"
          :customRow="customRow"
      >
        <template #title>
          <a-row justify="end">
            <a-col>
              <a-space>
                <a-button @click="downLoadClick" :loading="isExport"
                >
                  <template #icon>
                    <DownloadOutlined/>
                  </template>
                  导出报表
                </a-button
                >
                <a-button
                    @click="addPaymentNoticeBatch"
                    v-if="isOverdueIncomeTable"
                >一键批量催缴
                </a-button
                >
                <custom-columns
                    :colUrl="colUrl"
                    :type="typeList"
                    :newIcon="true"
                    :resetType="resetType"
                    from="contractList"
                    @getColumns="getColumns"
                />
              </a-space>
            </a-col>
          </a-row>
        </template>

        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.slotKey === 'owner_name'">
            <span
                :class="record.owner_id ? 'link' : ''"
                @click.stop="onOwnerClick(record.owner_id)"
            >{{ text || "--" }}</span
            >
          </template>
          <template v-if="column.slotKey === 'proprietor_name'">
            <span
                :class="record.owner_id || record.proprietor_id ? 'link' : ''"
                @click.stop="onOwnerCollectClick(record)"
            >{{
                record.owner_id
                    ? record.owner_name
                    : record.proprietor_id
                        ? record.proprietor_name || record.owner_name
                        : "--"
              }}</span
            >
          </template>
          <template v-if="column.slotKey === 'room_number'">
            <span v-if="record.build_bind && record.build_bind.room.length > 0">
              <a
                  v-for="room in record.build_bind.room"
                  class="break-a"
                  @click.stop="
                  roomClick(
                    room,
                    record.build_bind.room,
                    record.build_bind.village.id
                  )
                "
              >{{
                  room.layer_name + "-" + room.room_name
                }}<text v-if="record.build_bind.room.length > 1">, </text>
              </a>
            </span>
            <span v-else>--</span>
          </template>

          <template v-if="column.slotKey === 'notice_status'">
            <!-- 0:未发送； 2：已发送 -->
            <a-tag color="#ff3141" v-if="text == 0">{{
                record.notice_status_txt
              }}
            </a-tag>
            <a-tag color="#00b578" v-else>{{ record.notice_status_txt }}</a-tag>
          </template>

          <template v-if="column.slotKey === 'contract_number'">
            <span
                :class="record.contract_id ? 'link' : ''"
                @click.stop="onContractClick(record.contract_id)"
            >{{ text || "--" }}</span
            >
          </template>

          <template
              v-if="
              column.slotKey === 'settle_status' ||
              column.slotKey === 'settle_status_txt'
            "
          >
            {{ record.settle_status_txt || "--" }}
          </template>
          <template
              v-if="
              column.slotKey === 'currency' || column.slotKey === 'currency_txt'
            "
          >
            {{ record.currency_txt || "--" }}
          </template>
          <template v-if="column.slotKey === 'cost_type'">
            {{ record.cost_type_txt || "--" }}
          </template>

          <template v-if="column.slotKey === 'action'">
            <a-button
                type="link"
                size="small"
                @click.stop="addPaymentNoticeBatch('one', record.id)"
                style="margin-left: 10px"
            >催缴
            </a-button
            >
          </template>
        </template>
      </a-table>
    </div>

    <!-- 租客详情 -->
    <OwnerDetailDrawer
        :visible="ownerDetailVisible"
        :id="ownerId"
        @cancel="ownerDetailVisible = false"
    />

    <!-- 房间详情 -->
    <RoomDrawer
        :visible="visibleDetails"
        @cancel="btnCancelDetails"
        :maxRoomNumber="maxRoomNumber"
        :detail="roomDetail"
    />

    <!-- 业主详情 -->
    <CreateProprietor
        :visible="proprietorDetailVisible"
        :id="proprietorId"
        drawerType="view"
        @onClose="proprietorDetailVisible = false"
    />

    <!--  生成缴费通知单  -->
    <add-notice
        @closeDrawer="addNoticeVisible = false"
        @success="addNoticeVisible = false"
        :visible="addNoticeVisible"
        :ids="addNoticeIds"
    >
    </add-notice>

    <!--  合同详情  -->
    <ContractDetailDrawer
        :visible="contractDetailVisible"
        :id="contractDetailId"
        @handleCancel="
        () => {
          contractDetailVisible = false;
        }
      "
    />

    <!-- 导出表格 -->
    <ExportComponents
        v-if="isExport"
        :visible="isExport"
        :title="titles"
        url="/bill/list"
        service="/org"
        method="post"
        :params="paramses"
        :limit="1000"
        :columnstitle="listHanders"
        :custom_result="array"
        :custom_data="true"
        @customDataFunc="customResult"
        @request="$utils.commonRequest"
        @cancel="changeexport"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  ref,
  defineAsyncComponent,
  createVNode,
} from "vue";
import {
  DeleteOutlined,
  DownloadOutlined,
  ExclamationCircleOutlined,
  InsertRowAboveOutlined,
  SearchOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import {useRouter, useRoute} from "vue-router";
import {Form, message, notification, Empty, Modal} from "ant-design-vue";
import utils from "../../../common/utils/utils";
import dict from "../../../common/utils/dict";
import CustomColumns from "@/components/CustomColumns/index.vue";
import {xlsx} from "../../../common/utils/xlsx";

const useForm = Form.useForm;
import store from "@/store";
import OwnerDetailDrawer from "@/views/village/OwnerManage/modules/OwnerDetailDrawer.vue";
import CreateProprietor from "@/views/contract/CostContract/modules/CreateProprietor.vue";
import AddNotice from "@/views/bill/AllBills/AddNotice.vue";
import {ExportComponents} from "bl-common-vue3";
import dayjs, {Dayjs} from "dayjs";
import _ from "lodash";

const monthFormat = "YYYY-MM";
const RoomDrawer = defineAsyncComponent(() =>
    import("../../../components/village/RoomDrawer.vue")
);
import BLCOMMON from "bl-common-vue3";

const dateFormatStr = "YYYY-MM-DD";
const ContractDetailDrawer = defineAsyncComponent(() =>
    import("@/views/contract/ContractDetail/ContractDetailDrawer.vue")
);

export default defineComponent({
  name: "overdueBillList",
  components: {
    DeleteOutlined,
    AddNotice,
    OwnerDetailDrawer,
    InsertRowAboveOutlined,
    DownloadOutlined,
    SearchOutlined,
    RoomDrawer,
    CreateProprietor,
    Empty,
    ContractDetailDrawer,
    CustomColumns,
    ExportComponents,
  },
  setup() {
    const $router = useRouter();
    const $route = useRoute();

    const state = reactive({
      activeTab: "1", //  默认应收 1   应支 2
      dataList: [],
      loading: false,
      page: 1,
      limit: 10,
      total: 0,
      costTypeOption: [], // 费用类型下拉
      timeoutOption: [], // 逾期状态下拉
      lateFeeOption: [], // 滞纳金状态下拉
      remitTypeOption: [], // 收款方式下拉
      settleOption: [], // 结清状态下拉
      buildOption: [], // 收支楼宇下拉
      billSourceOption: [], // 账单来源下拉
      currencyOption: [], // 币种下拉
      ownerId: 0,
      ownerDetailVisible: false,
      proprietorId: 0,
      proprietorDetailVisible: false,
      addNoticeVisible: false,
      addNoticeIds: [],
      basicsInfo: {}, // 基础信息展示
      contractDetailVisible: false,
      contractDetailId: 0,
      buildList: [], // 楼宇
      villageList: [], // 项目
      villageAndBuildList: [], // 请求接口后缓存
      companyList: [],

      colUrl: {
        server: "/org",
        url: "/bill/overdueListColumn",
      },
      resetType: "autoBillOverdueListColumn",
      typeList: "user_billOverdue_list_field",

      overdueColumns: [],
      isExport: false,

      paramses: {},
      listHanders: {},
      array: [],
    });

    const sorterCols = ["owner_name", "timeout_days_txt_overdue"];

    const getColumns = (data) => {
      let arr = [];
      data.forEach((item) => {
        if (item.checked) {
          let col = {
            title: item.title,
            dataIndex: item.key,
            slotKey: item.key,
            width: item.width || 150,
          };
          if (sorterCols.includes(item.key)) {
            col.sorter = true;
          }
          // if (item.key == "cost_type") {
          //   item.key = "cost_type_txt";
          // }
          arr.push(col);
        }
      });

      state.overdueColumns = [...arr];
      state.overdueColumns = overdueColumn(arr);
      state.page = 1;
      getTableData();
    };

    const overdueColumn = (arr) => {
      let _columns = arr.map((v) => {
        if (titleChangeCol[v.dataIndex]) {
          v.title = titleChangeCol[v.dataIndex][state.activeTab];
        }
        if (priceCols.includes(v.dataIndex)) {
          v.customRender = ({text, record, index}) => {
            return text || "--";
          };
        }
        return v;
      });
      if (state.activeTab == "2") {
        // 逾期付款账单没有催缴
        _columns = _columns.filter((v) => v.slotKey !== "action");
      }
      return _columns;
    };

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));

    const rowSelection = computed(() =>
        ["1"].includes(state.activeTab)
            ? {
              selectedRowKeys: selectedRowKeys.value,
              onChange: onSelectedRowChange,
            }
            : null
    );

    const titleChangeCol = {
      receivable_payment: {
        1: "应收金额",
        2: "应付金额",
      },
      actual_payment: {
        1: "实收金额",
        2: "实付金额",
      },
      actual_retreat: {
        1: "需收金额",
        2: "需付金额",
      },
      receivable_payment_date: {
        1: "应收日期",
        2: "应付日期",
      },
    };

    const priceCols = [
      "bill_amount",
      "actual_retreat",
      "receivable_payment",
      "actual_payment",
      "receivable_latefee",
      "invoice_amount",
      "adjust_amount",
      "out_amount",
      "into_amount",
      "tax_rate",
      "tax_amount",
    ];

    // 搜索参数
    const searchParams = reactive({
      // 收支
      bill_source: undefined, // 账单来源
      cost_type: undefined, // 费用类型
      latefee_status: undefined, // 滞纳金状态
      start_date: undefined, // 开始时间
      end_date: undefined, // 结束时间
      currency: undefined, // 币种
      createdTime: undefined,
      created_start_at: undefined,
      created_end_at: undefined,
      settle_status: undefined, // 结清状态
      receivableTime: undefined,
      receivable_start_date: undefined,
      receivable_end_date: undefined,
      village_ids: [],
      build_ids: [],
      keywords: "",
      org_branch_id: [],
    });

    /* 逾期收表格 */
    const isOverdueIncomeTable = computed(() =>
        ["1"].includes(state.activeTab)
    );
    /* 逾期支表格 */
    const isOverdueExpenseTable = computed(() =>
        ["2"].includes(state.activeTab)
    );

    const overdueSettleOptions = computed(() => {
      if (["1"].includes(state.activeTab)) {
        return state.settleOption.filter((v) =>
            ["部分结清", "待收款"].includes(v.label)
        );
      } else if (["2"].includes(state.activeTab)) {
        return state.settleOption.filter((v) =>
            ["未付款", "部分结清"].includes(v.label)
        );
      } else {
        return state.settleOption;
      }
    });

    // 点击行
    const handleTableRowClick = (record) => {
      const query = {billId: record.id};
      $router.push({
        name: "billDetail",
        query,
      });
    };

    // 自定义行
    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => handleTableRowClick(record),
      };
    };

    // 选择应收账单
    const selectedRowKeys = ref([]);
    const onSelectedRowChange = (keys) => {
      if (keys.length > 100) {
        notification.warning({
          message: "警告",
          description: "您最多可勾选100项",
        });
        return;
      }
      selectedRowKeys.value = keys;
    };

    const {resetFields} = useForm(searchParams, {});

    const getTableData = (init = false) => {
      if (!state.isExport) {
        state.loading = true;
      }
      if (init) {
        state.page = 1;
        state.dataList = [];
        state.total = 0;
        state.basicsInfo = {};
        selectedRowKeys.value = [];
      }
      let params = {
        page: state.isExport ? 1 : state.page,
        limit: state.isExport ? 100000 : state.limit,
        sort: sort.value,
        order: order.value,
      };
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          if (
              ["bill_source", "cost_type"].includes(key) &&
              searchParams[key]?.length
          ) {
            params[key] = searchParams[key][searchParams[key].length - 1];
          } else if (
              ["settle_status", "org_branch_id"].includes(key) &&
              searchParams[key]?.length
          ) {
            params[key] = searchParams[key].join(",");
          } else {
            params[key] = searchParams[key];
          }
        }
      }
      delete params.createdTime;
      delete params.receivableTime;
      if (!params.settle_status) {
        params.settle_status = overdueSettleOptions.value
            .map((v) => v.value)
            .join(",");
      }
      if (isOverdueIncomeTable.value) {
        params.overdue_filter = "1";
      }
      if (isOverdueExpenseTable.value) {
        params.overdue_filter = "2";
      }
      state.paramses = params;
      return new Promise((resolve) => {
        request
            .post("/org", "/bill/list", params)
            .then((res) => {
              if (!state.isExport) {
                state.dataList = res.list;
                state.total = res.total;
                state.basicsInfo = res;
                return;
              }
              if (selectedRowKeys.value.length) {
                let list = [];
                selectedRowKeys.value.forEach((rowKey) => {
                  res.list.forEach((item) => {
                    if (rowKey == item.id) {
                      list.push(item);
                    }
                  });
                });
                resolve(list);
                return;
              }
              resolve(res.list);
            })
            .finally(() => {
              state.loading = false;
            });
      });
    };

    const handleRangePickerChange = (date, dateString) => {
      searchParams.created_start_at = dateString[0] || undefined;
      searchParams.created_end_at = dateString[1] || undefined;
    };

    const handleReceivablePickerChange = (date, dateString) => {
      searchParams.receivable_start_date = dateString[0] || undefined;
      searchParams.receivable_end_date = dateString[1] || undefined;
    };

    const onTabChange = () => {
      searchParams.settle_status = undefined;
      getTableData(true);
    };

    const reset = () => {
      resetFields();
      getTableData(true);
    };

    const removeUndefined = (obj) => {
      return Object.keys(obj)
          .filter((key) => obj[key] !== undefined)
          .reduce((result, key) => {
            result[key] = obj[key];
            return result;
          }, {});
    };

    // 导出报表

    const titles = computed(() => {
      return state.activeTab == 1 ? "逾期收款账单" : "逾期付款账单";
    });

    const downLoadClick = () => {
      let handerData = utils.deepClone(state.overdueColumns);
      state.listHanders = handerData.reduce((obj, v) => {
        obj[v.slotKey] = v.title;
        if (v.slotKey == "settle_status") {
          obj[v.slotKey] = undefined;
          v.slotKey = undefined;
          obj["settle_status_txt"] = v.title;
        }
        if (v.slotKey == "currency") {
          obj[v.slotKey] = undefined;
          v.slotKey = undefined;
          obj["currency_txt"] = v.title;
        }
        if (v.slotKey == "cost_type") {
          obj[v.slotKey] = undefined;
          v.slotKey = undefined;
          obj["cost_type_txt"] = v.title;
        }
        if (v.slotKey == "notice_status") {
          obj[v.slotKey] = undefined;
          v.slotKey = undefined;
          obj["notice_status_txt"] = v.title;
        }
        return obj;
      }, {});
      state.isExport = true;
    };

    const customResult = (ExportList) => {
      ExportList.forEach((item) => {
        item.actual_retreat = Number(item.actual_retreat);
        item.bill_amount = Number(item.bill_amount);
        item.receivable_payment = Number(item.receivable_payment);
        item.actual_payment = Number(item.actual_payment);
      });
      state.array = ExportList;
    };

    const changeexport = () => {
      state.isExport = false;
      message.success("导出成功,请等待文件生成");
    };

    // 一键批量催缴
    const addPaymentNoticeBatch = (type, id) => {
      let params = [];
      let isCover = false;
      if (type === "one" && id) {
        params = [id];
      } else if (selectedRowKeys.value.length) {
        isCover = true;
        params = selectedRowKeys.value;
      } else {
        params = state.basicsInfo?.overdueBillIds || [];
      }
      if (params.length) {
        request
            .post("/org", "/notice/beforeVerify", {
              billIds: params,
              needMsg: true,
            })
            .then((res) => {
              if (res.data.pass) {
                if (isCover) {
                  selectedRowKeys.value = res.data.matchIds;
                }
                state.addNoticeIds = res.data.matchIds;
                state.addNoticeVisible = true;
              } else {
                Modal.confirm({
                  title: "提示",
                  content: () => res.msg,
                  icon: () => createVNode(ExclamationCircleOutlined),
                  centered: true,
                  okText: () => "继续",
                  onOk() {
                    if (isCover) {
                      selectedRowKeys.value = res.data.matchIds;
                    }
                    state.addNoticeIds = res.data.matchIds;
                    state.addNoticeVisible = true;
                  },
                });
              }
            })
            .catch((err) => {
              console.log(err);
              if (err.code == 60023) {
                Modal.info({
                  title: "提示",
                  content: () => err.msg,
                  centered: true,
                  okText: () => "确定",
                });
              }
            });
      } else {
        message.warning("暂无数据~");
      }
    };
    const sort = ref("");
    const order = ref("");
    const handleTableChange = (pager, filters, sorter) => {
      state.dataList = [];
      if (sorter) {
        if (sorter.order) {
          sort.value = sorter.order == "ascend" ? "asc" : "desc";
          order.value = sorter.field;
          if (order.value == "timeout_days_txt") {
            order.value = "receivable_payment_date";
          }
          if (order.value == "owner_name") {
            order.value = "owner_id";
          }
        } else {
          order.value = "";
          sort.value = "";
        }
      }
      state.page = pager.current;
      state.limit = pager.pageSize;
      getTableData();
    };

    /** 查看租客 */
    const onOwnerClick = (id) => {
      if (id) {
        state.ownerId = id;
        state.ownerDetailVisible = true;
      }
    };
    /** 查看租客 || 业主 */
    const onOwnerCollectClick = (record) => {
      if (record.owner_id) {
        state.ownerId = record.owner_id;
        state.ownerDetailVisible = true;
      } else if (record.proprietor_id) {
        if (record.is_new == 1) {
          state.ownerId = record.proprietor_id;
          state.ownerDetailVisible = true;
        } else {
          state.proprietorId = record.proprietor_id;
          state.proprietorDetailVisible = true;
        }
      }
    };

    const handleSearch = () => {
      getTableData(true);
    };

    // 获取最大房源号
    const getMaxRoomNumber = (list) => {
      let max = 0;
      for (let room of list) {
        if (max < Number(room.room_number)) {
          max = Number(room.room_number);
        }
      }
      return max;
    };

    // 房间点击详情
    const maxRoomNumber = ref(0);
    const visibleDetails = ref(false);
    const roomDetail = ref({});

    const roomClick = (room, room_list, village_id) => {
      let roomData = room;
      roomData.village_id = village_id;
      roomDetail.value = roomData;
      maxRoomNumber.value = getMaxRoomNumber(room_list);
      visibleDetails.value = true;
    };

    const btnCancelDetails = () => {
      visibleDetails.value = false;
    };

    const getCostTypeSub = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      request
          .get("/org", "/bill/costList", {
            page: 1,
            limit: 9999,
            category_id: targetOption.value,
            status: 1,
          })
          .then((res) => {
            if (res.list) {
              targetOption.loading = false;
              targetOption.children = res.list.map((item) => ({
                label: item.name,
                value: item.cost_type,
                isLeaf: true,
              }));
              state.costTypeOption = [...state.costTypeOption];
            }
          });
    };

    const getCostTypeList = () => {
      request.get("/org", "/bill/cost/categoryList", {}).then((res) => {
        if (res.list) {
          state.costTypeOption = res.list.map((item) => ({
            label: item.name,
            value: item.id,
            isLeaf: false,
          }));
        }
      });
    };

    // 合同详情
    const onContractClick = (id) => {
      if (id) {
        state.contractDetailId = id;
        state.contractDetailVisible = true;
      }
    };

    // 项目楼宇筛选
    const getBuildList = () => {
      request
          .get("/org", "/build/villageAndBuildList/v2", {
            checked: 1,
          })
          .then((res) => {
            state.villageAndBuildList = res.villageList;
            state.buildList = [];
            state.villageList = [];
            let vList = [];
            let bList = [];
            res.villageList.forEach((village) => {
              vList.push({
                label: village.name,
                value: village.id,
              });
              village?.buildList?.forEach((build) => {
                bList.push({
                  label: build.build_name,
                  value: build.id,
                });
              });
            });
            state.villageList = _.cloneDeep(vList);
            state.buildList = _.cloneDeep(bList);
          });
    };

    const onVillageChange = (value, option) => {
      let vbList = _.cloneDeep(state.villageAndBuildList);
      let bList = [];
      if (value.length > 0) {
        vbList = state.villageAndBuildList.filter((village) =>
            value.includes(village.id)
        );

        // 筛选项目时清除楼宇选中项
        searchParams.build_ids = [];
      }
      vbList.forEach((village) => {
        if (village.buildList && village.buildList.length > 0) {
          village?.buildList?.forEach((build) => {
            bList.push({
              label: build.build_name,
              value: build.id,
            });
          });
        }
      });
      state.buildList = bList;
    };

    const init = () => {
      store.dispatch("BillInit").then((data) => {
        state.timeoutOption = data?.timeout_status || [];
        state.lateFeeOption = data?.latefee_status || [];
        state.remitTypeOption = data?.remit_type || [];
        state.settleOption = data?.settle_status || [];
        state.billSourceOption = data?.bill_source || [];
        state.currencyOption = data?.currency || [];
        state.adjustTypeOption = data?.adjust_type || [];
        state.companyList = data?.org_branch_id || [];
        getCostTypeList();
        getBuildList();
        getTableData();
      });
    };

    init();

    return {
      ...toRefs(state),
      searchParams,
      statementTabs,
      monthFormat,
      pagination,
      selectedRowKeys,
      visibleDetails,
      maxRoomNumber,
      roomDetail,
      isOverdueIncomeTable,
      isOverdueExpenseTable,
      dateFormatStr,
      rowSelection,
      overdueSettleOptions,
      BLCOMMON,
      reset,
      handleTableChange,
      onTabChange,
      onOwnerClick,
      handleSearch,
      onSelectedRowChange,
      roomClick,
      btnCancelDetails,
      onOwnerCollectClick,
      getCostTypeSub,
      handleRangePickerChange,
      handleReceivablePickerChange,
      onContractClick,
      addPaymentNoticeBatch,
      customRow,
      onVillageChange,
      getColumns,
      downLoadClick,
      titles,
      changeexport,
      customResult,
    };
  },
});

const statementTabs = [
  {
    key: "1",
    title: "逾期收款账单",
  },
  {
    key: "2",
    title: "逾期付款账单",
  },
];

const OVERDUE_COLUMNS = [
  {
    title: "对方名称",
    dataIndex: "owner_name",
    key: "owner_name_overdue",
    slotKey: "proprietor_name",
    width: 120,
    sorter: true,
    fixed: "left",
  },
  {
    title: "楼宇名称",
    key: "build_name_overdue",
    dataIndex: "build_name",
    width: 120,
  },
  {
    title: "合同编号",
    dataIndex: "contract_number",
    key: "contract_number_overdue",
    slotKey: "contract_number",
    width: 240,
  },
  {
    title: "结清状态",
    key: "settle_status_txt_overdue",
    dataIndex: "settle_status_txt",
    width: 120,
  },
  {
    title: "逾期天数",
    key: "timeout_days_txt_overdue",
    dataIndex: "timeout_days_txt",
    sorter: true,
    width: 120,
  },
  {
    title: "费用类型",
    key: "cost_type_txt_overdue",
    dataIndex: "cost_type_txt",
    width: 150,
  },
  {
    title: "租赁数",
    key: "lease_square_overdue",
    dataIndex: "lease_square",
    width: 120,
    customRender: ({text, record, index}) => {
      return text ? text + record.lease_square_unit : "--";
    },
  },
  {
    title: "账单来源",
    key: "bill_source_txt_overdue",
    dataIndex: "bill_source_txt",
    width: 120,
  },

  {
    title: "账单金额",
    key: "bill_amount_overdue",
    dataIndex: "bill_amount",
    width: 120,
  },
  {
    title: "应收金额",
    key: "receivable_payment_overdue",
    dataIndex: "receivable_payment",
    width: 120,
  },
  {
    title: "实收金额",
    dataIndex: "actual_payment",
    key: "actual_payment_overdue",
    width: 120,
  },
  {
    title: "需收金额",
    key: "actual_retreat_overdue",
    dataIndex: "actual_retreat",
    width: 120,
  },
  {
    title: "税率",
    key: "tax_rate",
    dataIndex: "tax_rate",
    width: 120,
  },
  {
    title: "税额",
    key: "tax_amount",
    dataIndex: "tax_amount",
    width: 120,
  },
  {
    title: "应收日期",
    key: "receivable_payment_date",
    dataIndex: "receivable_payment_date",
    width: 150,
  },
  {
    title: "开始日期",
    key: "start_date",
    dataIndex: "start_date",
    width: 150,
  },
  {
    title: "结束日期",
    key: "end_date",
    dataIndex: "end_date",
    width: 150,
  },
  {
    title: "缴费通知单",
    key: "notice_status_overdue",
    dataIndex: "notice_status",
    slotKey: "notice_status",
    width: 120,
  },
  {
    title: "调整金额",
    key: "adjust_amount",
    dataIndex: "adjust_amount",
    width: 150,
  },
  {
    title: "转出金额",
    key: "out_amount",
    dataIndex: "out_amount",
    width: 120,
  },
  {
    title: "转入金额",
    key: "into_amount",
    dataIndex: "into_amount",
    width: 120,
  },
  {
    title: "币种",
    key: "currency_txt_overdue",
    dataIndex: "currency_txt",
    width: 100,
  },
  {
    title: "操作",
    key: "action_overdue",
    dataIndex: "id",
    slotKey: "action",
    fixed: "right",
    width: 120,
  },
];
</script>

<style lang="less" scoped>
.bill-statement {
  padding: 10px;

  .tab-row {
    background: #fff;
    padding: 0 10px;
  }

  .search-row {
    margin: 10px 0 0 0 !important;
    background: #fff;
    padding: 16px 0 0 0;
  }

  :deep(.ant-tabs-bar) {
    margin: 0;
  }

  :deep(.ant-radio-button-wrapper) {
    padding: 0 18px;
  }

  .statement-content {
    margin-top: 1px;
    background: #fff;
    padding: 0 10px;
  }

  .title-card-text {
    height: 40px;
    width: 100%;
    font-size: 16px;
    font-weight: bold;
    color: rgba(0, 0, 0, 0.8);
    position: relative;
    padding: 20px 12px;
    display: flex;
    align-items: center;

    &::before {
      position: absolute;
      content: "";
      left: 0;
      top: 12px;
      bottom: 12px;
      width: 6px;
      border-radius: 4px;
      background-color: @primary-color;
    }
  }

  :deep(.ant-card-head-title) {
    padding: 4px 0;
  }

  .total-box {
    width: 100%;
    padding: 0 20px;
    display: flex;
  }

  .total-item {
    flex: 1;
    display: flex;
    align-items: center;
    width: 0;
    margin-right: 10px;
  }

  .dec-left {
    justify-content: left;
  }

  .dec-right {
    justify-content: right;
  }

  .item-dec {
    display: flex;
    flex-direction: column;
    align-items: center;
    max-width: 100%;
    height: 60px;
    justify-content: space-between;
  }

  .total-num {
    max-width: 100%;
    font-size: 22px;
    font-weight: 600;
    word-break: break-all;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }

  .total-dec {
    max-width: 100%;
    color: #666;
    font-weight: 600;
    font-size: 14px;
    word-break: break-all;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }

  .border-right {
    border-right: 1px solid #ddd;
  }

  :deep(.ant-card-extra) {
    padding: 0;
  }
}

:deep(.ant-spin-nested-loading) {
  height: 100%;
}

:deep(.ant-spin-container) {
  height: 100%;
}

.overview-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .custom-legend {
    height: 50px;
    width: 100%;
    display: flex;
    justify-content: space-between;

    &-item {
      display: flex;
      flex-direction: column;
      flex: 1;
      align-items: center;
      justify-content: space-around;

      .item-count {
        font-size: 18px;
        font-weight: 600;
        color: #666666;
      }

      .item-title {
        display: flex;
        font-size: 12px;
        align-items: center;
      }

      &:not(:last-child) {
        border-right: 1px solid #e9e9e9;
      }
    }
  }

  .chart {
    flex: 1;
  }
}

.circle {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 2px;
}

.break-a {
  word-break: break-all;
  display: block;
}

.statistics {
  margin-top: 10px;

  .quantity {
    width: 100%;
    background-color: #fff;
    height: 120px;
    align-items: center;
    padding: 10px;

    .text-center {
      text-align: center;
      position: relative;
      flex: 1;
      width: 0;

      .text {
        color: #8d8d8d;
      }

      .number-width {
        color: @primary-color;
        font-weight: 700;
        font-size: 26px;
        width: 100%;
        // 文字不折行
        overflow: hidden;
        word-break: break-all;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }

  .text-center:not(:last-child):after {
    content: "";
    position: absolute;
    right: 0;
    top: 25%;
    height: 50%;
    border-left: 1px solid #e6e5e5;
  }
}
</style>
